// 管理员商品管理
<template>
  <div class="product-manage">
    <div class="d-flex justify-content-between align-items-center mb-4">
      <h2>商品管理</h2>
      <router-link to="/admin/products/add" class="btn btn-success">
        <i class="bi bi-plus-circle"></i> 添加商品
      </router-link>
    </div>

    <table class="table table-hover">
      <thead>
      <tr>
        <th>ID</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>库存</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="product in products" :key="product.id">
        <td>{{ product.id }}</td>
        <td>{{ product.name }}</td>
        <td>¥{{ product.price }}</td>
        <td>{{ product.stock }}</td>
        <td>
          <router-link
              :to="`/admin/products/edit/${product.id}`"
              class="btn btn-sm btn-primary me-2"
          >
            编辑
          </router-link>
          <button
              class="btn btn-sm btn-danger"
              @click="deleteProduct(product.id)"
          >
            删除
          </button>
        </td>
      </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { productApi } from '@/api'

export default {
  setup() {
    const products = ref([])

    const loadProducts = async () => {
      try {
        products.value = await productApi.getAll()
      } catch (error) {
        console.error('加载商品失败:', error)
      }
    }

    const deleteProduct = async (id) => {
      if (!confirm('确定要删除这个商品吗？')) return

      try {
        await productApi.delete(id)
        products.value = products.value.filter(p => p.id !== id)
        alert('商品已删除')
      } catch (error) {
        console.error('删除商品失败:', error)
      }
    }

    onMounted(loadProducts)

    return {
      products,
      deleteProduct
    }
  }
}
</script>